<?php

namespace App\Http\Controllers;

use App\Exceptions\InvalidRequestException;
use App\Models\Product;
use Illuminate\Http\Request;

class ProductsController extends Controller
{
    //
    public function index(Request $request)
    {
        $queryBuilder = Product::onSales();
        if ($search = $request->input('search', '')) {
            $like = '%' . $search . '%';
            $queryBuilder->where(function ($query) use ($like) {
                $query->where('title', 'like', $like)
                    ->orWhere('description', 'like', $like)
                    ->orWhereHas('skus', function ($query) use ($like) {
                        $query->where('title', 'like', $like)
                            ->orWhere('description', 'like', $like);
                    });
            });
        }

        if ($order = $request->input('order', '')) {
            if (preg_match('/^(.+)_(asc|desc)$/', $order, $m)) {
                if (in_array($m[1], ['price', 'sold_count', 'rating'])) {
                    $queryBuilder->orderBy($m[1], $m[2]);
                }
            }
        }
        $filters = ['search' => $search, 'order' => $order];
        $products = $queryBuilder->paginate(16);
        return view('products.index', compact('products', 'filters'));
    }

    public function show(Product $product, Request $request)
    {
        $favored = false;
        if (!$product->on_sale) {
            throw new InvalidRequestException('商品未上架');
        }
        $user = $request->user();
        $favored = boolval($user->favoriteProducts()->find($product->id));
        return view('products.show', compact('product','favored'));
    }

    public function favor(Product $product, Request $request): array
    {
        $user = $request->user();
        if ($user->favoriteProducts()->find($product->id)) {
            return [];
        }
        $user->favoriteProducts()->attach($product);
        return [];
    }

    public function disfavor(Product $product, Request $request): array
    {
        $user = $request->user();
        $user->favoriteProducts()->detach($product);
        return [];
    }

    public function favorites(Request $request)
    {
        $products = $request->user()->favoriteProducts()->paginate(16);
        return view('products.favorites',compact('products'));
    }
}
